package com.demo.rabbit.client.multconsumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeoutException;

public class WorkConsumer {
    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        ThreadGroup threadGroup = new ThreadGroup("work-consumer-thread-group");
        factory.setSharedExecutor(Executors.newFixedThreadPool(3,new ThreadFactory(){

            @Override
            public Thread newThread(Runnable r) {
                Thread thread =  new Thread(threadGroup,r);
                return thread;
            }
        }));
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel();
             Connection connection2 = factory.newConnection();
             Channel channel2 = connection2.createChannel()){
            channel.queueDeclare("queue1",false,false,false,null);

            channel.basicQos(1);
            channel.basicConsume("queue1", true, new DeliverCallback() {
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
                    System.out.println("Thread : "+Thread.currentThread().getId() + "   consumer 1 : " + new String(message.getBody(),"utf-8") + "  tag : "+consumerTag);
                }
            },consumerTag -> {});

            channel2.basicQos(1);
            channel2.basicConsume("queue1", true, new DeliverCallback() {
                @Override
                public void handle(String consumerTag, Delivery message) throws IOException {
                    System.out.println("Thread : "+Thread.currentThread().getId() + "   consumer 2 : " + new String(message.getBody(),"utf-8") + "  tag : "+consumerTag);
                }
            },consumerTag -> {});

            Scanner scanner = new Scanner(System.in);
            System.out.println("consumer exit with " + scanner.nextLine());
            System.exit(0);
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
